package servlet;

import dao.Dao;
import domain.Goods;
import domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addShoppingCarServlet")
public class AddShoppingCarServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String sid = request.getParameter("sid");
        String suserid = request.getParameter("suserid");
        String cnumber = request.getParameter("cnumber");
        Dao dao = new Dao();
        Goods goodByCid = dao.findGoodByCid(sid);
        User userById = dao.findUserById(Integer.valueOf(suserid));
        if (Integer.valueOf(cnumber) > goodByCid.getCnumber()) {
            request.setAttribute("AddShoppingCarInfo", "商品数量不足，请重新输入购买数量");
            request.getRequestDispatcher("/catchUserGoodInfoServlet").forward(request, response);
        } else {
            int i = dao.addShoppingCar(goodByCid, userById, Integer.valueOf(cnumber), (float) (Integer.valueOf(cnumber) * (goodByCid.getCprice() * goodByCid.getCdiscounte() / 10)));
            if (i > 0) {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            } else {
                request.setAttribute("/catchUserGoodInfoServlet", "添加购物车失败，请重试");
                request.getRequestDispatcher("/ShoppingCarInfo.jsp").forward(request, response);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
